const { where } = require("sequelize");
const TextFile = require("../Model/TextFile.model");
const Document = require("../Model/document.model");
const { update } = require("../Controller/textfile.controller");
const { text } = require("express");
class TextFileService {
  async CreateService(body) {
    const { filekind, iconUrl, fatherID } = body;
    const res = await TextFile.create({
      filekind,
      iconUrl,
      fatherID,
    });
    const doc = await Document.findOne({ where: { id: fatherID } });
    doc.fileContainInfo = doc.fileContainInfo
      ? [...doc.fileContainInfo, res.dataValues]
      : [res.dataValues];
    await doc.save();
    return res.dataValues;
  }
  async UpdateService(id, content) {
    const text = await TextFile.findOne({ where: { id } });
    text.filecontent = content;
    const doc = await Document.findByPk(text.fatherID);
    doc.fileContainInfo = doc.fileContainInfo.filter((item) => {
      if (item.id == id) {
        item.filecontent = content;
      }
      return item;
    });
    await Document.update(
      { fileContainInfo: doc.fileContainInfo },
      { where: { id: text.fatherID } }
    );
    // await doc.save();
    await text.save();
    return doc;
  }
  async renameService(id, NewName) {
    const text = await TextFile.findOne({ where: { id } });
    text.filename = NewName;
    const doc = await Document.findByPk(text.fatherID);
    doc.fileContainInfo = doc.fileContainInfo.filter((item) => {
      if (item.id == id) {
        item.filename = NewName;
      }
      return item;
    });
    await Document.update(
      { fileContainInfo: doc.fileContainInfo },
      { where: { id: text.fatherID } }
    );
    await text.save();
  }
  async DeleteService(id) {
    const res = await TextFile.findOne({ where: { id } });
    const doc = await Document.findOne({ where: { id: res.fatherID } });
    // user.hobbies = user.hobbies
    //   ? user.hobbies.filter((hobby) => hobby !== "reading")
    //   : null;
    // 在文件表删除数据
    doc.fileContainInfo = doc.fileContainInfo.filter((item) => {
      return item.id != id;
    });
    doc.save();
    // 在text表删除数据
    const nums = await TextFile.destroy({ where: { id } });
    return res;
  }
  async findService() {}
}

module.exports = new TextFileService();
